<template>
  <view class="purchase-container">
    <view class="wrap">
      <!-- #ifdef APP-PLUS -->
      <view class="custom-navbar">
        <view class="navbar-left" @click="goBack">
          <u-icon name="arrow-left" color="#fff" size="44"></u-icon>
        </view>
        <view class="navbar-title">云购活动</view>
        <view class="navbar-right"></view>
      </view>
      <!-- #endif -->
      <view class="nav-bar">
        <view class="left-nav" :class="{'active1': activeIndex == 0}" @click="handleClickNav(0)">
          <text class>已结束</text>
        </view>
        <view class="middle-nav" :class="{'active2': activeIndex == 1}" @click="handleClickNav(1)">
          <view style="margin-top: 10rpx;"></view>
          <u-count-down :timestamp="countdown" bg-color="#000" color="#fff" separator-color="#000"></u-count-down>
          <view style="margin-top: 2rpx;">进行中</view>
        </view>
        <view class="right-nav" :class="{'active3': activeIndex == 2}"  @click="handleClickNav(2)">
          可预购
        </view>
      </view>
    </view>
    <!-- 已结束 -->
     <view v-if="activeIndex == 0">
       <view class="goods-list app-list" v-if="goodsList1.length != 0">
         <view class="goods-item-box" v-for="(item, index) in goodsList1" :key="index">
           <view class="goods-item">
             <view class="goods-img">
               <image :src="item.good.image+'?='+new Date().getTime()" class="img" v-if="item.good"></image>
             </view>
             <view class="goods-info">
               <view class="goods-name" v-if="item.good">{{item.good.name}}</view>
               <view class="person-num">
                 <view><image src="../../static/person_num.png" class="person-img"></image></view>
                 <view class="person-txt">{{item.people_num}}人满员</view>
               </view>
               <u-line-progress active-color="#f30310" :percent="getNum(item.join_num, item.people_num)" height="20"></u-line-progress>
               <view class="bottom-info">
                 <view class="price-info">
                   <view class="sale-price" v-if="item.good">¥{{item.good.min_price}}</view>
                 </view>
               </view>
             </view>
           </view>
           <view class="line"></view>
           <view class="clock-txt">
            <u-icon name="bell-fill" color="#f4030f" size="34"></u-icon>
            <text>结束时间：{{item.end_time}}</text>
           </view>
         </view>
       </view>
       <view v-else class="empty-box">
         <image src="../../static/shop.png" class="empty-img"></image>
         <view>~ 暂无抢购活动 ~</view>
       </view>
     </view>
     <!-- 进行中 -->
     <view v-if="activeIndex == 1">
       <view class="goods-list app-list" v-if="goodsList2.length != 0">
         <view class="goods-item-box" v-for="(item, index) in goodsList2" :key="index">
           <view class="goods-item">
             <view class="goods-img">
               <image :src="item.good.image+'?='+new Date().getTime()" class="img"></image>
             </view>
             <view class="goods-info">
               <view class="goods-name">{{item.good.name}}</view>
               <view class="person-num">
                 <view><image src="../../static/person_num.png" class="person-img"></image></view>
                 <view class="person-txt">{{item.people_num}}人满员</view>
               </view>
               <view class="count">可参与{{item.count}}次</view>
               <u-line-progress active-color="#f30310" :percent="getNum(item.join_num, item.people_num)" height="20"></u-line-progress>
               <view class="bottom-info">
                 <view class="price-info">
                   <view class="sale-price">¥{{item.good.min_price}}</view>
                 </view>
                 <view class="btn" @click="handleClickBtn(item)" v-if="parseInt(item.people_num) != parseInt(item.join_num)">
                   去参与
                 </view>
                 <view class="over-btn" v-if="parseInt(item.people_num) == parseInt(item.join_num)" @click="handleClickOver">
                  人数已满
                 </view>
               </view>
             </view>
           </view>
           <view class="line"></view>
            <view class="clock-txt">
              <u-icon name="bell-fill" color="#f4030f" size="34"></u-icon>
              <text>{{item.start_time.split(' ')[0]}}</text>
            </view>
            <view class="clock-txt">
              <text>开始时间：{{item.start_time.split(' ')[1]}}</text><text>--</text><text>结束时间：{{item.end_time.split(' ')[1]}}</text>
            </view>
         </view>
       </view>
       <view v-else class="empty-box">
         <image src="../../static/shop.png" class="empty-img"></image>
         <view>~ 暂无抢购活动 ~</view>
       </view>
     </view>
     <!-- 预约开抢 -->
     <view v-if="activeIndex == 2">
       <view class="goods-list app-list" v-if="goodsList3.length != 0">
         <view class="goods-item-box" v-for="(item, index) in goodsList3" :key="index">
           <view class="goods-item">
             <view class="goods-img">
               <image :src="item.good.image+'?='+new Date().getTime()" class="img"></image>
             </view>
             <view class="goods-info">
               <view class="goods-name">{{item.good.name}}</view>
               <view class="person-num">
                 <view><image src="../../static/person_num.png" class="person-img"></image></view>
                 <view class="person-txt">{{item.people_num}}人满员</view>
               </view>
               <view class="count">可参与{{item.count}}次</view>
               <u-line-progress active-color="#f30310" :percent="getNum(item.join_num, item.people_num)" height="20"></u-line-progress>
               <view class="bottom-info">
                 <view class="price-info">
                   <view class="sale-price">¥{{item.good.min_price}}</view>
                 </view>
                 <view class="btn" @click="handleClickBtn3(item)" v-if="parseInt(item.people_num) != parseInt(item.join_num)" :join="item.join_num" :people="item.people_num">
                   去预购
                 </view>
                 <view class="over-btn" v-if="parseInt(item.people_num) == parseInt(item.join_num)" @click="handleClickOver">
                  人数已满
                 </view>
               </view>
             </view>
           </view>
           <view class="line"></view>
           <view class="clock-txt">
              <u-icon name="bell-fill" color="#f4030f" size="34"></u-icon>
              <text>{{item.start_time.split(' ')[0]}}</text>
            </view>
            <view class="clock-txt">
              <text>开抢时间：{{item.start_time.split(' ')[1]}}</text><text>--</text><text>结束时间：{{item.end_time.split(' ')[1]}}</text>
            </view>
         </view>
       </view>
       <view v-else class="empty-box">
         <image src="../../static/shop.png" class="empty-img"></image>
         <view>~ 暂无抢购活动 ~</view>
       </view>
     </view>
  </view>

</template>
<script>
import {
  getSecondBuyList, getSecondBuyExist
} from "@/api/activity";
 export default {
  data() {
    return {
      goodsList1: [],
      goodsList2: [],
      goodsList3: [],
      countdown: null,
      navStyle: {
        backBg: 0.4,
        backgroundBg: 0,
        backColor: 'rgba(256,256,256,1)'
      },
      activeIndex: 1,
    }
  },
  mounted() {
    this.getData();
      // #ifdef H5
      this.getEventSource();
      // #endif
  },
  computed: {
    getNum() {
      return function(v1, v2) {
        // console.log(v1);
        // console.log(v2);
        let tempNum = parseInt((v1/v2)*100);
        console.log('tempNum');
        console.log(tempNum);
        return tempNum;
      }
    }
  },
  methods: {
    getEventSource() {
      // H5端连接sse请求，监听消息
        const source = new EventSource('https://asytest.jiuhuashi.com/sse');
        source.addEventListener('open', function(event) {
              console.log('连接已成功建立');
        });
        source.addEventListener('message', (event) => {
              // console.log('收到消息H5端:', event);
              console.log('收到消息:', event.data);
              // console.log('收到消息:', typeof event.data);
              if (!event.data) {
                return;
              }
              let tempObj = JSON.parse(event.data);
              // console.log('收到消息:', typeof tempObj);
              // console.log(this.goodsList2);
              //这是推送的商品列表
              if (tempObj.action == 'second_buy_list') {
                console.log('收到消息2:', tempObj.data);
                this.countdown = null;
                this.countdown = tempObj.data.countdown;
                this.goodsList1 = [];
                this.goodsList2 = [];
                this.goodsList3 = [];
                this.goodsList1 = tempObj.data.list.expired;
                this.goodsList2 = tempObj.data.list.ing;
                this.goodsList3 = tempObj.data.list.reserve;
              }
              //这是人数增加的
              if (tempObj.action == 'second_buy_push') {
                let secondBuyId = tempObj.second_buy_id;
                if (this.goodsList2.length != 0) {
                  for (let i = 0; i < this.goodsList2.length; i++) {
                    if (this.goodsList2[i].id == secondBuyId) {
                      if (this.goodsList2[i].join_num != this.goodsList2[i].people_num) {
                        this.goodsList2[i].join_num++;
                        this.getNum(this.goodsList2[i].join_num, this.goodsList2[i].people_num);
                      }
                      console.log(this.goodsList2[i].join_num);
                      console.log(this.goodsList2[i].people_num);
                    }
                  }
                }
                if (this.goodsList3.length != 0) {
                  for (let j = 0; j < this.goodsList3.length; j++) {
                    if (this.goodsList3[j].id == secondBuyId) {
                      if (this.goodsList3[j].join_num != this.goodsList3[j].people_num) {
                        this.goodsList3[j].join_num++;
                        this.getNum(this.goodsList3[j].join_num, this.goodsList3[j].people_num);
                      }
                      console.log(this.goodsList3[j].join_num);
                      console.log(this.goodsList3[j].people_num);
                    }
                  }
                }
              }
        });
        source.addEventListener('error', function(event) {
          if (event.eventPhase == EventSource.CLOSED) {
            console.log('连接已关闭');
          } else {
            console.log('连接发生错误');
          }
        });

    },
    handleClickOver() {
      this.$toast({
				title: '该活动人数已满',
			})
    },
    handleClickNav(i) {
      console.log(i);
      this.activeIndex = i;
      // console.log(this.goodsList1);
      // console.log(this.goodsList2);
      // console.log(this.goodsList3);
    },
    onPullDownRefresh() {
      this.getData();
    },
    getData() {
      uni.showLoading({
        mask: true,
        title: '数据加载中...'
      })
      getSecondBuyList().then(res => {
        uni.hideLoading();
        uni.stopPullDownRefresh();
        console.log(res);
        this.countdown = res.data.countdown;
        console.log(this.countdown);
        this.goodsList1 = res.data.list.expired;
        this.goodsList2 = res.data.list.ing;
        this.goodsList3 = res.data.list.reserve;
      })
    },
    goBack() {
      uni.navigateBack({
        delta: 1
      });
		},
    handleClickBtn3(v) {
      let id = v.id;
      let goodId = v.good_id;
      // console.log(v);
      // console.log(v.good_id);
      console.log(v.people_num);
      console.log(v.join_num);
      let peopleNum = parseInt(v.people_num);
      let joinNum = parseInt(v.join_num);
      getSecondBuyExist(id).then(res => {
        console.log(res);
        if (res.data.length != 0) {
          this.$toast({
            title:  res.msg,
          })
          return;
        }
        if (peopleNum == joinNum) {
          // console.log('coming');
          this.$toast({
            title: '该活动已满员',
          })
        } else {
          uni.navigateTo({
            url: '/pages/goods_details/goods_details?id=' + goodId + '&is_second_buy=1' + '&second_buy_id=' + id + '&goodsType=' + -1,
          })
        }
      })
    },
    handleClickBtn(v) {
      let id = v.id;
      let goodId = v.good_id;
      // console.log(v);
      // console.log(v.good_id);
      console.log(v.people_num);
      console.log(v.join_num);
      let peopleNum = parseInt(v.people_num);
      let joinNum = parseInt(v.join_num);
      if (peopleNum == joinNum) {
        // console.log('coming');
        this.$toast({
          title: '该活动已满员',
        })
      } else {
        uni.navigateTo({
          url: '/pages/goods_details/goods_details?id=' + goodId + '&is_second_buy=1' + '&second_buy_id=' + id + '&goodsType=' + -1,
        })
      }
    },
    // 接收到来自 renderjs 的数据
    acceptDataFromRenderjs(options) {
			console.log('接收到来自 renderjs 的数据APP端：', options);	
      if (!options.messageData) {
        return; 
      }
			let tempObj = options.messageData;
      console.log(tempObj);
      if (tempObj.action == 'second_buy_list') {
          console.log('收到消息2:', tempObj.data);
          this.countdown = null;
          this.countdown = tempObj.data.countdown;
          this.goodsList1 = [];
          this.goodsList2 = [];
          this.goodsList3 = [];
          this.goodsList1 = tempObj.data.list.expired;
          this.goodsList2 = tempObj.data.list.ing;
          this.goodsList3 = tempObj.data.list.reserve;
      }
      if (tempObj.action == 'second_buy_push') {
        let secondBuyId = tempObj.second_buy_id;
        if (this.goodsList2.length != 0) {
          for (let i = 0; i < this.goodsList2.length; i++) {
            if (this.goodsList2[i].id == secondBuyId) {
              if (this.goodsList2[i].join_num != this.goodsList2[i].people_num) {
                this.goodsList2[i].join_num++;
                this.getNum(this.goodsList2[i].join_num, this.goodsList2[i].people_num);
              }
              console.log(this.goodsList2[i].join_num);
              console.log(this.goodsList2[i].people_num);
            }
          }
        }
        if (this.goodsList3.length != 0) {
          for (let j = 0; j < this.goodsList3.length; j++) {
            if (this.goodsList3[j].id == secondBuyId) {
              if (this.goodsList3[j].join_num != this.goodsList3[j].people_num) {
                this.goodsList3[j].join_num++;
                this.getNum(this.goodsList3[j].join_num, this.goodsList3[j].people_num);
              }
              console.log(this.goodsList3[j].join_num);
              console.log(this.goodsList3[j].people_num);
            }
          }
        }
      }
		},
  }
}
</script>
<script module="renderScript" lang="renderjs">
import { EventSourcePolyfill } from '@/js_sdk/event-source-polyfill'

export default {
  data() {
    return {
      IsSupportSse: 'EventSource' in window,
    }
  },
  mounted() {
    // #ifdef APP
    console.log('APP-PLUS');
    window.addEventListener('beforeunload', () => {
      this.source.close(); // 页面关闭时关闭连接
    });
    this.sse(); // 初始化 SSE 连接
    // #endif
  },
  methods: {
    // 发送数据到service层
    emitData() {
      // #ifdef APP
      UniViewJSBridge.publishHandler('onWxsInvokeCallMethod', {
        cid: this._$id,
        method: 'acceptDataFromRenderjs',
        args: {
          messageData: this.messageData
        }
      })
      // #endif
      // #ifdef H5
      var options = {
        messageData:this.messageData
      };
      this.acceptDataFromRenderjs(options);
      // #endif
    },
    // 初始化 SSE 连接
    sse() {
      if ('EventSource' in window) {
        // console.log('SSE 连接中...');
        // console.log(EventSourcePolyfill);
        this.source = new EventSourcePolyfill('https://auth.jiuhuashi.com/sse');
        this.source.onmessage = (e) => {
          // console.log('---接收到服务器推送的数据---');
		  		// console.log(e.data);
          this.messageData = e.data; // 接收服务器推送的数据
					// console.log(this.messageData);
          this.emitData(); // 发送数据到 service 层
        };
        this.source.onopen = () => {
          console.log('---连接打开---');
        };
        this.source.onerror = (e) => {
          if (e.readyState === EventSource.CLOSED) {
            console.log('---连接关闭---');
          } else {
            console.log('onerror:', e.readyState);
          }
        };
      } else {
        console.log('当前环境不支持 SSE');
      }
    },
  },
}
</script>
<style lang="scss">

	page {
		color: #fff;
		font-family: "PingFang SC", "Helvetica Neue", Arial, sans-serif;
	}

	.purchase-container {
		padding-bottom: 60rpx;
    background: #F5F5F5;
    // height: 180vh;
    margin-top: 110rpx;
  }

  .custom-navbar {
    height: 128rpx;
    padding-top: var(--status-bar-height);
    // background-image: linear-gradient(135deg, #ff2e2a 0%, #ff2e2a 100%);
    background: #0199fe;
    display: flex;
    align-items: center;
    padding-left: 30rpx;
    padding-right: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
    line-height: 100rpx;
    
    .navbar-left {
      width: 100rpx;
      display: flex;
      align-items: center;
    }
    
    .navbar-title {
      flex: 1;
      text-align: center;
      font-size: 36rpx;
      font-weight: bold;
      color: #fff;
      text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
    }
    
    .navbar-right {
      width: 100rpx;
    }
  }

  .goods-list {
    margin: 20rpx;
    padding-bottom: 100rpx;
  }
  // #ifdef APP-PLUS
  .app-list {
    margin-top: 238rpx;
  }
  // #endif

  .goods-item-box {
    min-height: 190rpx;
    background: #fff;
    border-radius: 20rpx;
    margin-bottom: 20rpx;
    padding: 20rpx;
  }
  
  .goods-item {
    width: 100%;
    display: inline-flex;
  }

  .goods-img {
    // float: left;
    display: inline-flex;
    width: 234rpx;
    height: 232rpx;
    background: #f7f7f7;
    border-radius: 20rpx;
  }
  
  .img {
    width: 100%;
    height: 100%;
    border-radius: 20rpx;
  }

  .goods-info {
    width: 60%;
    // display: inline-flex;
    margin-left: 20rpx;
  }

  .goods-name {
    font-size: 30rpx;
    color: #010101;
    font-weight: 600;
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden; /* 隐藏溢出的内容 */
    text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本 */
    margin-bottom: 20rpx;
  }

  .goods-spec {
    font-size: 28rpx;
    color: #010101;
    margin: 10rpx 0;
  }

  .person-num {
    width: 170rpx;
    height: 33rpx;
    border: 1px solid #f4020e;
    border-radius: 20rpx;
    display: flex;
    justify-content: flex-start;
    margin-bottom: 10rpx;
  }

  .person-img {
    width: 30rpx;
    height: 30rpx;
  }

  .person-txt {
    color: #f4020e;
    line-height: 33rpx;
    font-size: 24rpx;
    margin-left: 10rpx;
  }

  ::v-deep .uni-progress-bar {
    border-radius: 10px;
  }

  ::v-deep .uni-progress-inner-bar {
    border-radius: 10px;
    // overflow: hidden;
  }

  ::v-deep .uni-progress-info {
    color: #f4020e
  }

  .bottom-info {
    // display: flex;
    // justify-content: space-around;
  }

  .origin-price {
    color: #b1b1b1;
    text-decoration: line-through;
    font-size: 24rpx;
  }

  .sale-price {
    color: #f42d42;
    font-size: 36rpx;
    font-weight: 600;
    margin-top: 35rpx;
  }

  .price-info {
    float: left;
  }

  .btn {
    float: right;
    margin-top: 20rpx;
    width: 145rpx;
    height: 56rpx;
    background: url(../../static/btn.png);
    background-repeat: no-repeat;
		background-size: 100%;
    border-radius: 10rpx;
    text-align: center;
    line-height: 56rpx;
    font-size: 30rpx;
  }

  .over-btn {
    float: right;
    margin-top: 20rpx;
    width: 145rpx;
    height: 56rpx;
    background: #ccc;
    border-radius: 10rpx;
    text-align: center;
    line-height: 56rpx;
    font-size: 30rpx;
    color: #fff;
  }

  .empty-img {
  width: 240rpx;
  height: 240rpx;  
  }

.empty-box {
  text-align: center;
  margin-top: 400rpx;
  font-size: 26rpx;
  color: #7a7474;
}

.line {
  margin-top: 20rpx;
  border-top: 1rpx solid #eee;
}

.clock-txt {
  color: #ff4d4f;
  // display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20rpx;
  font-size: 26rpx;
  font-weight: 600;
  text-align: center;
  // vertical-align: middle;
}

.clock-txt text {
  display: inline-block;
  margin-left: 10rpx;
  margin-right: 10rpx;
}

.clock-txt2 text{
  margin-left: 40rpx;
}

.wrap {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 99999;
}

.nav-bar {
  width: 750rpx;
  height: 92rpx;
  background: #0199fe;
  display: flex;
  text-align: center;
  justify-content: space-between;
}

.left-nav {
  width: 256rpx;
  height: 94rpx;
  font-size: 30rpx;
  text-align: center;
  color: #fff;
  line-height: 94rpx;

}

.left-nav.active1 {
  background: url(../../static/left_icon.png);
  background-repeat: no-repeat;
  background-size: 100%;
  width: 256rpx;
  height: 94rpx;
  color: #0199fe;
}

.middle-nav {
  width: 256rpx;
  height: 94rpx;
}

.middle-nav.active2 {
  background: url(../../static/middle_icon.png);
  background-repeat: no-repeat;
  background-size: 100%;
  width: 256rpx;
  height: 94rpx;
  color: #0199fe;
}


.right-nav {
  width: 256rpx;
  height: 94rpx;
  font-size: 30rpx;
  text-align: center;
  line-height: 94rpx;
  color: #fff;
}

.right-nav.active3 {
  background: url(../../static/right_icon.png);
  background-repeat: no-repeat;
  background-size: 100%;
  width: 256rpx;
  height: 94rpx;
  color: #0199fe;
}

.count {
  color: #ff4d4f;
  font-size: 24rpx;
  margin: 20rpx 0 10rpx;
}

</style>